package com.guoguo.controller;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.BaseController;
import com.guoguo.enums.UsersEnum;
import com.guoguo.service.UploadService;
import com.guoguo.utils.FileUtils;
import com.guoguo.utils.PropertyUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by KLSD on 2017/9/12.
 */
@Controller
@RequestMapping("/view")
public class SystemController extends BaseController {
    @Resource
    private UploadService uploadService;
    @RequestMapping(value = "/system", method = RequestMethod.GET)
    public ModelAndView system() {
        Map<String, Object> data = new HashMap<>();

        String freeImgNums = PropertyUtils.getProperty("sms.properties", "sms.freeImgNum");
        data.put("freeImgNum", freeImgNums);

        return returnView("/system", data);

    }

    @RequestMapping(value = "/saveSystem", method = RequestMethod.POST)
    public JSONObject saveSystem(String freeImgNum) {
        Map<String, Object> data = new HashMap<>();
        data.put("freeImgNum", PropertyUtils.setProperty("sms.properties", "sms.freeImgNum", freeImgNum));

        return returnResult(200, data, "");

    }


    /**
     * 上传管理
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/upload",method=RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
        String path = request.getSession().getServletContext().getRealPath("/download");
        String fileName = file.getOriginalFilename();
        File dir = new File(path,fileName);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);
        return "ok!";
    }

}